package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@Tag(name = "回复接口")
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;

    @Operation(summary = "创建文章回复")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @Param("帖子id") @RequestParam("articleId") @NonNull Long articleId,
                            @Param("帖子内容") @RequestParam("content") @NonNull String content) {

        // 1. 获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 获取帖子信息
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 是否封贴
        if(article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 构建回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);  // 要回复的帖子id
        articleReply.setPostUserId(user.getId());    // 回复的用户id
        articleReply.setContent(content);    // 回复的内容

        // 2. 调用service
        articleReplyService.create(articleReply);
        return AppResult.success();
    }

    @Operation(summary = "获取文章回复列表")
    @GetMapping("/getReplies")
    private AppResult<List<ArticleReply>> getRepliesByArticleId(@Param("文章id") @RequestParam("articleId") @NonNull Long articleId) {
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        return AppResult.success(articleReplies);
    }
}
